<?php

// connect to database
$conn_str = 'host=dbsrv1.cdf.toronto.edu dbname=csc309g23 user=csc309g23 password=ipheid5h';
$conn = pg_connect($conn_str);

// query database
$query = 'INSERT INTO members (username, firstname, lastname, email, password,gender,display) VALUES (\'' . $_POST['username'] . '\',\'' . $_POST['firstname'] . '\',\'' . $_POST['lastname'] . '\',\'' . $_POST['email'] . '\',\'' . $_POST['password'] . '\',\'' . $_POST['gender'] . '\',\'profiles/user.dp.default\')';

if ($result = pg_query($conn, $query)) {

    // query database
    $query = 'SELECT * FROM members WHERE username=\'' . $_POST['username'] . '\' and password=\'' . $_POST['password'] . '\'';
    $result = pg_query($conn, $query);

    if ($row = pg_fetch_assoc($result)) { // check username and password match

        // start session
        session_start();

        // save all user info and preferences in a session
        $_SESSION['username'] = $row['username'];
        $_SESSION['firstname'] = $row['firstname'];
        $_SESSION['lastname'] = $row['lastname'];
        $_SESSION['email'] = $row['email'];
        $_SESSION['address'] = $row['address'];
        $_SESSION['question'] = $row['question'];
        $_SESSION['answer'] = $row['answer'];
        $_SESSION['display'] = $row['display'];
        $_SESSION['playrating'] = $row['playrating'];
        $_SESSION['playgames'] = $row['playgames'];
        $_SESSION['orgrating'] = $row['orgrating'];
        $_SESSION['orggames'] = $row['orggames'];
        $_SESSION['showfirstname'] = $row['showfirstname'];
        $_SESSION['showlastname'] = $row['showlastname'];
        $_SESSION['showbirthday'] = $row['showbirthday'];
        $_SESSION['showemail'] = $row['showemail'];
        $_SESSION['showaddress'] = $row['showaddress'];
        $_SESSION['country'] = $row['country'];
        $_SESSION['city'] = $row['city'];

	header('Location: /home.php');
	}

} else {
	// go back to page from which user logged in
	header('Location: ' . $_SERVER['HTTP_REFERER']);
}

?>
